package com.geek.gkpush.util.http;

import org.apache.commons.collections.CollectionUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1>Cookie相关处理工具类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-19
 *
 */
public class CookieUtils {

    /**
     * <h2>解析并获取 Cookie。</h2>
     *
     * @param request
     * @return
     */
    public static Map<String, Cookie> parseCookies(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (!CollectionUtils.sizeIsEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * <h2>从 cookies 里面通过 name 获取对应的 value。</h2>
     *
     * @param cookieMap
     * @param name
     * @return
     */
    public static Object getValue(Map<String, Cookie> cookieMap, String name) {
        if (cookieMap == null || cookieMap.isEmpty()) {
            return null;
        }

        Cookie cookie = cookieMap.get(name);
        if (cookie == null) {
            return null;
        }

        return cookie.getValue();
    }
}